//
// Created by Suny on 14-11-18.
// Copyright (c) 2014 Suny. All rights reserved.
//

#import "SelectTableViewController.h"
#import "UIBarButtonItem+BaseFramework.h"
#import "ChineseToPinyin.h"
#import "UIImageView+WebCache.h"
#import "SelectTableViewCell.h"
#import "TabViewController.h"
#import "TipView.h"

@interface SelectTableViewController ()

@property(nonatomic, strong) NSMutableArray *sectionTitles;
@property(nonatomic, strong) NSMutableArray *dataSourceArray;

@property(nonatomic,strong)TipView *tipView;

@end

@implementation SelectTableViewController

- (id)init
{
    self = [super init];
    if (self)
    {
        self.tableViewCellStyle = UITableViewCellStyleValue1;
		self.selectedArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = self.defaultBackButtonItem;

    [self.view addSubview:self.tableView];


}


#pragma mark -


- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,
                                                                   self.navigationBarHeight,
                                                                   self.view.width,
                                                                   self.view.height - self.navigationBarHeight - self.customTabViewController.tabBarHeight)
                                                  style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate   = self;

        _tableView.allowsMultipleSelectionDuringEditing = self.isMultiSelect;
        [_tableView setEditing:self.isMultiSelect];

    }
    return _tableView;
}

- (NSMutableArray *)sectionTitles
{
    if (!_sectionTitles)
    {
        _sectionTitles = [NSMutableArray array];
    }

    return _sectionTitles;
}



- (void)setNormalSourceArray:(NSMutableArray *)normalSourceArray
{
    _normalSourceArray = normalSourceArray;
    _dataSourceArray = [self sortDataArray:normalSourceArray];
}


- (void)reloadSelectItems
{
    [self.tableView reloadData];
}

- (void)setIsMultiSelect:(BOOL)isMultiSelect
{
    _isMultiSelect = isMultiSelect;
    self.tableView.allowsMultipleSelectionDuringEditing = isMultiSelect;

    if (isMultiSelect)
    {
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightBarButtonItemWithTitle:@"完成"
                                                                                       target:self
                                                                                     selector:@selector(commitSelectArray)];
    }
    else
    {
        self.navigationItem.rightBarButtonItem = nil;
    }
}

- (NSMutableArray *)sortDataArray:(NSArray *)dataArray
{
    //建立索引的核心
    UILocalizedIndexedCollation *indexCollation = [UILocalizedIndexedCollation currentCollation];

    [self.sectionTitles removeAllObjects];
    [self.sectionTitles addObjectsFromArray:[indexCollation sectionTitles]];

    //返回27，是a－z和＃
    NSInteger      highSection  = [self.sectionTitles count];
    //tableView 会被分成27个section
    NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:(NSUInteger) highSection];
    for (int       i            = 0; i <= highSection; i++)
    {
        NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:1];
        [sortedArray addObject:sectionArray];
    }

    //名字分section
    for (NSObject <SelectTableViewItemDelegate> *item in dataArray)
    {
        //getUserName是实现中文拼音检索的核心，见NameIndex类
        NSString *firstLetter = nil;
        if ([item respondsToSelector:@selector(selectTableViewIteNameString)])
        {
            firstLetter = [ChineseToPinyin pinyinFromChineseString:[item selectTableViewIteNameString]];
        }
        NSInteger section = [indexCollation sectionForObject:[firstLetter substringToIndex:1]
                                     collationStringSelector:@selector(uppercaseString)];

        NSMutableArray *array = [sortedArray objectAtIndex:(NSUInteger) section];
        [array addObject:item];
    }

    //每个section内的数组排序
    for (NSUInteger i = 0; i < [sortedArray count]; i++)
    {
        NSArray *array = [[sortedArray objectAtIndex:i] sortedArrayUsingComparator:^NSComparisonResult(NSObject <SelectTableViewItemDelegate> *obj1,
                                                                                                       NSObject <SelectTableViewItemDelegate> *obj2)
                {
                    NSString *firstLetter1 = nil;
                    if ([obj1 respondsToSelector:@selector(selectTableViewIteNameString)])
                    {
                        firstLetter1 = [ChineseToPinyin pinyinFromChineseString:[obj1 selectTableViewIteNameString]];
                        firstLetter1 = [[firstLetter1 substringToIndex:1] uppercaseString];
                    }

                    NSString *firstLetter2 = nil;
                    if ([obj2 respondsToSelector:@selector(selectTableViewIteNameString)])
                    {
                        firstLetter2 = [ChineseToPinyin pinyinFromChineseString:[obj2 selectTableViewIteNameString]];
                        firstLetter2 = [[firstLetter2 substringToIndex:1] uppercaseString];
                    }

                    return [firstLetter1 caseInsensitiveCompare:firstLetter2];
                }];


        [sortedArray replaceObjectAtIndex:i
                               withObject:[NSMutableArray arrayWithArray:array]];
    }

    return sortedArray;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [self.dataSourceArray count] + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section == 0)
    {
        return [self.topSourceArray count];
    }
    else
    {
        return [[self.dataSourceArray objectAtIndex:(NSUInteger) (section - 1)] count];
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SelectTableViewCell *cell;
    static NSString     *CellIdentifier = @"SelectTableViewCell";
    cell = (SelectTableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...
    if (cell == nil)
    {
        cell = [[SelectTableViewCell alloc] initWithStyle:self.tableViewCellStyle
                                          reuseIdentifier:CellIdentifier];
    }
	
	if (CHECK_VALID_STRING(self.cellImageHoderName))
	{
		cell.imageHoderName = self.cellImageHoderName;
	}

	if (!_isMultiSelect)
	{
		cell.selectionStyle = UITableViewCellSelectionStyleNone;

	}
    cell.indexPath = indexPath;
    NSObject <SelectTableViewItemDelegate> *item = nil;

    if (indexPath.section == 0)
    {
         item = [self.topSourceArray safeObjectAtIndex:indexPath.row];
    }
    else
    {
        item = [[self.dataSourceArray safeObjectAtIndex:(NSUInteger) (indexPath.section - 1)] safeObjectAtIndex:(NSUInteger) indexPath.row];

    }

    cell.item = item;
    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 || [[self.dataSourceArray objectAtIndex:(NSUInteger) (section - 1)] count] == 0)
    {
        return 0;
    }
    else
    {
        if (self.showAlphaForSectionHeader)
        {
            return 22;
        }
        else
        {
            return  0;
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0 || [[self.dataSourceArray objectAtIndex:(NSUInteger) (section - 1)] count] == 0)
    {
        return nil;
    }
    if (self.showAlphaForSectionHeader)
    {
        UIView *contentView = [[UIView alloc] init];
        [contentView setBackgroundColor:[UIColor colorWithRed:0.88
                                                        green:0.88
                                                         blue:0.88
                                                        alpha:1.0]];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100, 22)];
        label.backgroundColor = [UIColor clearColor];
        [label setText:[self.sectionTitles objectAtIndex:(NSUInteger) (section - 1)]];
        [contentView addSubview:label];
        return contentView;
    }
    else
    {
        return nil;
    }

}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *existTitles = [NSMutableArray array];

    if (self.showAlphaIndex)
    {
        //section数组为空的title过滤掉，不显示
        for (int       i            = 0; i < [self.sectionTitles count]; i++)
        {
            if ([[self.dataSourceArray objectAtIndex:i] count] > 0)
            {
                [existTitles addObject:[self.sectionTitles objectAtIndex:i]];
            }
        }
    }

    return existTitles;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
	//建立索引的核心
	UILocalizedIndexedCollation *indexCollation = [UILocalizedIndexedCollation currentCollation];
	int section = [[indexCollation sectionTitles] indexOfObject:title];
	if (CHECK_VALID_ARRAY(self.topSourceArray))
	{
		section += 1;
	}
//	
//	if (!self.tipView)
//	{
//		self.tipView = [TipView showWithTitle:title type:TipType_none];
//	}
//	else
//	{
//		self.tipView.hidden = YES;
//		
//		self.tipView = [TipView showWithTitle:title type:TipType_none];
//
//
//	}
	
	return section;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	id <SelectTableViewItemDelegate> item ;
	if (indexPath.section == 0)
	{
		item = [self.topSourceArray objectAtIndex:(NSUInteger)indexPath.row];
	}
	else
	{
		item = [[self.dataSourceArray objectAtIndex:(NSUInteger) (indexPath.section - 1)] objectAtIndex:(NSUInteger) indexPath.row];
	}
	
    if (!tableView.editing)
    {

		[self.delegate selectContactViewController:self
									 selectedArray:@[item]];

    }
	else
	{
		
		if (![self.selectedArray containsObject:item])
		{
			[self.selectedArray addObject:item];
		}
		
	}
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (tableView.editing)
	{
		
	 id <SelectTableViewItemDelegate> item ;
	 if (indexPath.section == 0)
	 {
		 item = [self.topSourceArray objectAtIndex:(NSUInteger)indexPath.row];
	 }
	 else
	 {
		 item = [[self.dataSourceArray objectAtIndex:(NSUInteger) (indexPath.section - 1)] objectAtIndex:(NSUInteger) indexPath.row];
	 }
	 
	 if ([self.selectedArray containsObject:item])
	 {
		 [self.selectedArray removeObject:item];
	 }
	}
}


- (void)commitSelectArray
{
    NSArray *array = self.selectedArray;

    BOOL finish = [self.delegate selectContactViewController:self
                                               selectedArray:array];
	
	if (finish)
	{
		[self dismissViewControllerAnimated:NO completion:nil];
	}

}




- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{
	
	if (tableView.editing)
	{
		return UITableViewCellEditingStyleNone;

	}
	else
	{
		if (self.allowSlideDelete)
		{
			return UITableViewCellEditingStyleDelete;

		}
		else
		{
			return UITableViewCellEditingStyleNone;
		}
	}

}


#pragma mark - private


#pragma mark - Table view data source


// Override to support editing the table view.
- (void) tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {

        id buddy         = [[self.dataSourceArray objectAtIndex:(NSUInteger) (indexPath.section - 1)] objectAtIndex:(NSUInteger) indexPath.row];


        [[self.dataSourceArray objectAtIndex:(NSUInteger) (indexPath.section - 1)] removeObjectAtIndex:(NSUInteger) indexPath.row];
        [self.dataSourceArray removeObject:buddy];

        if ([self.delegate selectContactViewController:self
                                            deleteItem:buddy])
        {
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                             withRowAnimation:UITableViewRowAnimationFade];
            [tableView endUpdates];
        }

    }
}

- (BOOL)navigationController:(NavigationController *)navigationController shouldNavigateInteractiveGestureRecognizerBegin:(UIGestureRecognizer *)gestureRecognizer
{
	if (self.tableView.editing)
	{
		return NO;
	}
	else
	{
		__block BOOL allow = YES;
		NSArray *array = self.tableView.visibleCells;
		[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
			UITableViewCell *cell = obj;

			if (cell.showingDeleteConfirmation)
			{
				allow = NO;
				*stop = YES;
			}	
		}];
		
		return allow;
	}
}
@end